import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import '../models/essay_material.dart';
import '../repositories/essay_material_repository.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:device_info_plus/device_info_plus.dart';
import '../widgets/image_preview_widget.dart';

class AddEditEssayMaterialScreen extends StatefulWidget {
  final int? materialId;
  
  const AddEditEssayMaterialScreen({super.key, this.materialId});

  @override
  State<AddEditEssayMaterialScreen> createState() => _AddEditEssayMaterialScreenState();
}

class _AddEditEssayMaterialScreenState extends State<AddEditEssayMaterialScreen> {
  final _formKey = GlobalKey<FormState>();
  final _titleController = TextEditingController();
  final _contentController = TextEditingController();
  
  String _selectedCategory = '人物素材';
  bool _isLoading = false;
  bool _isEditMode = false;
  File? _imageFile;
  final _imagePicker = ImagePicker();
  
  // 分类选项
  final List<String> _categories = [
    '人物素材',
    '社会热点',
    '环境保护',
    '科技发展',
    '文化传承',
  ];
  
  @override
  void initState() {
    super.initState();
    _isEditMode = widget.materialId != null;
    
    if (_isEditMode) {
      _loadMaterialData();
    }
  }
  
  Future<void> _loadMaterialData() async {
    setState(() => _isLoading = true);
    
    try {
      // 从数据库加载素材数据
      final essayMaterialRepository = EssayMaterialRepository();
      final material = await essayMaterialRepository.getEssayMaterialById(widget.materialId!);
      
      if (material == null) {
        throw Exception('未找到素材');
      }
      
      setState(() {
        _titleController.text = material.title;
        _contentController.text = material.content;
        _selectedCategory = material.category;
        // 如果有图片路径，加载图片
        if (material.imageUrl != null && material.imageUrl!.isNotEmpty) {
          _imageFile = File(material.imageUrl!);
        }
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      _showErrorSnackBar('加载素材数据失败: $e');
      print('加载素材数据错误: $e'); // 添加错误日志
    }
  }
  
  // 获取存储路径的方法
  Future<String> _getStoragePath() async {
    // 检查是否为桌面平台
    if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
      // 桌面平台使用固定路径
      return 'D:\\000\\my-web\\学习宝库\\图片\\作文素材';
    }
    
    // 移动平台处理
    if (Platform.isAndroid) {
      final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      final AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      
      // 请求存储权限
      final status = await Permission.storage.request();
      if (!status.isGranted) {
        throw Exception('需要存储权限才能保存图片');
      }
      
      // 获取存储目录
      Directory? directory;
      try {
        // 尝试获取外部存储目录
        directory = await getExternalStorageDirectory();
        if (directory == null) {
          throw Exception('无法获取外部存储目录');
        }
        
        // 构建路径：Download/考试宝/图片/作文素材
        String basePath = directory.path;
        // 如果路径包含Android/data，则需要回退到外部存储根目录
        if (basePath.contains('Android/data')) {
          List<String> paths = basePath.split('/');
          int index = paths.indexOf('Android');
          if (index > 0) {
            // 回退到外部存储根目录
            basePath = paths.sublist(0, index).join('/');
          }
        }
        
        return path.join(basePath, 'Download', '学习宝库', '图片', '作文素材');
      } catch (e) {
        print('获取存储路径失败: $e');
        // 如果无法获取外部存储，则使用应用内部存储
        directory = await getApplicationDocumentsDirectory();
        return path.join(directory.path, 'Download', '学习宝库', '图片', '作文素材');
      }
    } else if (Platform.isIOS) {
      // iOS平台使用应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      return path.join(directory.path, 'Download', '学习宝库', '图片', '作文素材');
    } else {
      // 其他平台使用临时目录
      final directory = await getTemporaryDirectory();
      return path.join(directory.path, 'Download', '学习宝库', '图片', '作文素材');
    }
  }
  
  // 选择图片
  Future<void> _pickImage() async {
    try {
      // 检查是否在Web平台
      if (kIsWeb) {
        // Web平台不支持本地文件选择
        _showErrorSnackBar('Web平台不支持本地图片上传');
        return;
      }
      
      final pickedFile = await _imagePicker.pickImage(source: ImageSource.gallery);
      if (pickedFile != null) {
        // 获取存储路径
        final String baseDir = await _getStoragePath();
        
        // 确保目录存在
        final directory = Directory(baseDir);
        if (!await directory.exists()) {
          await directory.create(recursive: true);
        }
        
        final fileName = path.basename(pickedFile.path);
        final String savedPath = Platform.isWindows 
            ? '$baseDir\\$fileName' 
            : path.join(baseDir, fileName);
        final savedImage = await File(pickedFile.path).copy(savedPath);
        
        print('图片已保存到: ${savedImage.path}'); // 添加日志以便调试
        
        setState(() {
          _imageFile = File(savedImage.path);
        });
      }
    } catch (e) {
      print('选择图片失败: $e');
      _showErrorSnackBar('选择图片失败: ${e.toString()}');
    }
  }
  
  // 删除已选择的图片
  void _removeImage() {
    setState(() {
      _imageFile = null;
    });
  }
  
  Future<void> _saveMaterial() async {
    if (!_formKey.currentState!.validate()) return;
    
    setState(() => _isLoading = true);
    
    try {
      // 获取当前时间戳
      final now = DateTime.now().millisecondsSinceEpoch;
      
      // 处理图片路径
      String? imageUrl;
      if (_imageFile != null) {
        // 图片已经在_pickImage方法中复制到了永久存储目录
        // 直接使用该路径
        imageUrl = _imageFile!.path;
      }
      
      // 创建仓库实例
      final essayMaterialRepository = EssayMaterialRepository();
      
      // 创建作文素材对象
      final material = EssayMaterial(
        id: _isEditMode ? widget.materialId : null,
        title: _titleController.text.trim(),
        content: _contentController.text.trim(),
        category: _selectedCategory,
        tags: '', // 可以在界面中添加标签输入
        source: '', // 可以在界面中添加来源输入
        imageUrl: imageUrl,
        createdAt: _isEditMode ? /* 原创建时间 */ now : now,
        updatedAt: now,
      );
      
      // 保存到数据库
      if (_isEditMode) {
        await essayMaterialRepository.updateEssayMaterial(material);
      } else {
        await essayMaterialRepository.addEssayMaterial(material);
      }
      
      setState(() => _isLoading = false);
      _showSuccessSnackBar(_isEditMode ? '素材已更新' : '素材已创建');
      
      // 返回上一页，并传递刷新标志
      if (mounted) Navigator.pop(context, true); // 返回true表示需要刷新列表
    } catch (e) {
      setState(() => _isLoading = false);
      _showErrorSnackBar(_isEditMode ? '更新素材失败' : '创建素材失败');
      print('保存素材错误: $e'); // 添加错误日志
    }
  }
  
  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message)),
    );
  }
  
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }
  
  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isEditMode ? '编辑素材' : '添加素材'),
        centerTitle: true,
      ),
      body: _isLoading && _isEditMode
          ? const Center(child: CircularProgressIndicator())
          : Form(
              key: _formKey,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // 标题输入
                    TextFormField(
                      controller: _titleController,
                      decoration: const InputDecoration(
                        labelText: '标题',
                        border: OutlineInputBorder(),
                      ),
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return '请输入素材标题';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),
                    
                    // 分类选择
                    DropdownButtonFormField<String>(
                      value: _selectedCategory,
                      decoration: const InputDecoration(
                        labelText: '分类',
                        border: OutlineInputBorder(),
                      ),
                      items: _categories.map((category) {
                        return DropdownMenuItem<String>(
                          value: category,
                          child: Text(
                            category,
                            style: TextStyle(
                              color: Theme.of(context).textTheme.bodyLarge?.color ?? Colors.black,
                            ),
                          ),
                        );
                      }).toList(),
                      onChanged: (value) {
                        if (value != null) {
                          setState(() {
                            _selectedCategory = value;
                          });
                        }
                      },
                      style: TextStyle(
                        color: Theme.of(context).textTheme.bodyLarge?.color ?? Colors.black,
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请选择素材分类';
                        }
                        return null;
                      },
                    ),
                    const SizedBox(height: 16),
                    
                    // 内容输入
                    Expanded(
                      child: TextFormField(
                        controller: _contentController,
                        decoration: const InputDecoration(
                          labelText: '内容',
                          alignLabelWithHint: true,
                          border: OutlineInputBorder(),
                          hintText: '输入素材内容，支持多段落...',
                        ),
                        maxLines: null,
                        expands: true,
                        textAlignVertical: TextAlignVertical.top,
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return '请输入素材内容';
                          }
                          return null;
                        },
                      ),
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // 图片选择和预览
                    Card(
                      elevation: 2,
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const Text(
                                  '图片',
                                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                                ),
                                Row(
                                  children: [
                                    IconButton(
                                      icon: const Icon(Icons.add_photo_alternate, color: Colors.blue),
                                      onPressed: _pickImage,
                                      tooltip: '添加图片',
                                    ),
                                    if (_imageFile != null)
                                      IconButton(
                                        icon: const Icon(Icons.delete, color: Colors.red),
                                        onPressed: _removeImage,
                                        tooltip: '删除图片',
                                      ),
                                  ],
                                ),
                              ],
                            ),
                            if (_imageFile != null) ...[  
                              const SizedBox(height: 8),
                              ImagePreviewWidget(
                                imageUrl: _imageFile!.path,
                                height: 200,
                                width: double.infinity,
                                fit: BoxFit.contain,
                                showPath: true,
                              ),
                            ],
                          ],
                        ),
                      ),
                    ),
                    
                    const SizedBox(height: 16),
                    
                    // 保存按钮
                    ElevatedButton.icon(
                      onPressed: _isLoading ? null : _saveMaterial,
                      icon: _isLoading
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            )
                          : const Icon(Icons.save),
                      label: Text(_isEditMode ? '更新素材' : '保存素材'),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}